//
//  THGossipHeaderView.swift
//  TongHuoDemo
//
//  Created by rimi on 2017/5/12.
//  Copyright © 2017年 rimi. All rights reserved.
//

import UIKit

class THGossipHeaderView: UIView {
    
    fileprivate var titleScrollView: UIScrollView!
    fileprivate var clickedBtn: UIButton?
    // 按钮的点击事件
    var titleBtnClickCallback: ((_ btn: UIButton) -> ())?
    // 标题数组
    var titleArray: [String]! {
        didSet {
            // 外界赋值标题后设置标题视图
            setupTitleBtn()
        }
    }
    
    // MARK: - UI相关
    override init(frame: CGRect) {
        super.init(frame: frame)
        titleArray = Array()
        titleScrollView = UIScrollView(frame: frame)
        titleScrollView.showsHorizontalScrollIndicator = false
        titleScrollView.bounces = false
        addSubview(titleScrollView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 添加标题按钮
    fileprivate func setupTitleBtn() {
        let W: CGFloat = 70
        for i in 0..<titleArray.count {
            let titleBtn = UIButton(type: .custom)
            titleBtn.frame = CGRect(x: W * CGFloat(i), y: 0, width: W, height: titleScrollView.frame.height)
            titleBtn.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
            titleBtn.setTitle(titleArray[i], for: .normal)
            titleBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
            titleBtn.setTitleColor(UIColor.black, for: .normal)
            titleBtn.setTitleColor(UIColor.orange, for: .selected)
            titleScrollView.addSubview(titleBtn)
            titleBtn.addTarget(self, action: #selector(titleBtnClicked(btn:)), for: .touchUpInside)
            // 设置默认选中
            if i == 0 {
                titleBtn.isSelected = true
                titleBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
                clickedBtn = titleBtn
            }
        }
        // 设置内容大小
        titleScrollView.contentSize = CGSize(width: W * CGFloat(titleArray.count), height: 0)
    }
    
    // 标题按钮的监听回调
    @objc fileprivate func titleBtnClicked(btn: UIButton) {
        // 恢复
        clickedBtn?.isSelected = false
        clickedBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        // 设置选中并记录
        btn.isSelected = true
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
        clickedBtn = btn
        
        // 传递事件给控制器
        titleBtnClickCallback?(btn)
    }

}
